import { createSlice } from "@reduxjs/toolkit"; 
import {  setToken as _setToken, getToken as _getToken,removeToken  } from '@/utils/index'
import { logintApi,getUserInfoApi} from '@/api/user'
const userStore = createSlice({
  name: "user",
  initialState: {
    token:_getToken( )||'',
    userInfo:{}
  },
  reducers: {
    setToken(stare, action) {
      stare.token = action.payload;
      _setToken( action.payload)
    },
    setUserInfo(stare, action) { 
      stare.userInfo = action.payload; 
    },
    clearUser(stare, action){
      stare.token =  ''
      stare.userInfo = {}
      removeToken()
    }
  },
});

const { setToken ,setUserInfo ,clearUser} = userStore.actions;
const getToken = (  data) => {
  return async (dispath) => { 
    let res = await logintApi(  data); 
    if (res.data.message === 'OK') {
      dispath(setToken(res.data.data.token)) 
      
      return true
    }
    return false
  };
};
const getUserInfo = (  data) => {
  return async (dispath) => { 
    let res = await getUserInfoApi()
    console.dir(res,'447553230000') 
      dispath(setUserInfo(res?.data?.data ||{})) 
      
      
  };
};


export { clearUser, getToken ,getUserInfo ,  };
export default userStore.reducer;
